package com.et114.modules.org.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.et114.components.acegi.Constants;
import com.et114.components.tree.tree51.BaseTree51Model;
import com.et114.core.action.BaseDispatchAction;
import com.et114.core.exception.CheckException;
import com.et114.core.utility.StringPool;
import com.et114.modules.org.form.GroupForm;
import com.et114.modules.org.message.FuncMessageManager;
import com.et114.modules.org.services.GroupManager;
import com.et114.modules.org.services.OrgFactory;
import com.et114.modules.org.utility.SessionUserInfo;
import com.et114.modules.org.utility.tree.OrgGroupTree;
import com.et114.modules.org.vo.GroupRelVo;
import com.et114.modules.org.vo.GroupVo;
import com.et114.modules.org.vo.RoleVo;
import com.et114.modules.org.vo.UserEmplyVo;

import org.acegisecurity.concurrent.SessionInformation;
import org.acegisecurity.concurrent.SessionRegistry;



//author zxy
public class OnLineUserAction extends BaseDispatchAction {
	int mxxlim = 500 ; 
	public ActionForward onLineIndex ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {
		return mapping.findForward ( "onLineIndex" );
	}

	public  ActionForward getGroupTrees( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		SessionUserInfo currentUser = getCurrentUser ( request );
		HttpSession session = request.getSession ( ) ; 
		GroupForm groupform = ( GroupForm ) form;
		GroupManager fm = OrgFactory.getGroupManager ( );
		//
		Long grpId = groupform.getGrpId ( );
		List els = new ArrayList();
		String partyTree;
		// session
		groupform.setCrtUser ( currentUser.getUserId ( ) );
		//
		if ( groupform.isValidGrpId ( ) ) {
			els = fm.getChildGroup (  grpId  );
			partyTree = generateGroupTreeStr ( fm , true , els , null , BaseTree51Model.IS_TARGET_N , request.getLocale ( ) );
		} else {
			if ( currentUser.getCurrentUserMaxRoleType ( ) < Constants.ROLE_TYPE_ORG_MANAGER ) {
				els = /*fm.getChildGroup ( new Long ( Constants.ORG_GROUP_BASE_VALUE ) ) ;//*/fm.getRootGroup ( );
			}
			else if ( currentUser.getCurrentUserMaxRoleType ( ) == Constants.ROLE_TYPE_ORG_MANAGER ) { 
				List roles = OrgFactory.getUserManager ( ).getAllRolesByUserParams  (
						Constants.ROLE_TYPE_ORG_MANAGER ,
						currentUser.getUserId ( ) );
				if ( roles.size ( ) > 0 ) {
					StringBuffer roleIds = new StringBuffer() ;
					for ( int i = 0 ; i < roles.size ( ) ; i ++ ) {
						RoleVo role = ( RoleVo ) roles.get ( i ) ;
						roleIds.append ( role.getRoleId ( ).toString ( ) )  ;
						if ( ( i + 1 ) != roles.size ( ) ) roleIds.append ( StringPool.COMMA )  ;
					}
					if ( roleIds.length ( ) > 0 ) {
						Map groupMap = OrgFactory.getRoleManager ( ).getGroupsAnByRoles ( roleIds.toString ( ) ) ;
						els =  OrgFactory.getRoleManager ( ).getRootsGroupsByRolesSorts( groupMap )  ; 												
						if ( els.size ( ) > 0  ) {
						}
						else {
						}
					}
				} 
			}
			else {
				els = /*fm.getChildGroup ( new Long ( Constants.ORG_GROUP_BASE_VALUE ) ) ;*/ fm.getRootGroup ( );
			}
			
			String cugid = null ; 
			String ist = BaseTree51Model.IS_TARGET_Y ; 
			if ( session.getAttribute ( BaseTree51Model.LOC_VALUES ) != null ) {
				cugid = session.getAttribute ( BaseTree51Model.LOC_VALUES ).toString ( ) ;
				ist = BaseTree51Model.IS_TARGET_N ; 
			}
			else if ( els.size ( ) > 0  ) 
				cugid = ( ( GroupVo ) els.get ( 0 ) ).getGrpId ( ).toString ( ) ;
			
			
			partyTree = generateGroupTreeStr ( fm ,  false , els , cugid , ist ,  new Locale (
					currentUser.getLanguage ( ) ) );
		}
		request.setAttribute ( "defaultTabName" , FuncMessageManager.get ( request.getLocale ( )  ).getMessage ( "group.tree.root" )  ) ; 		
		request.setAttribute (  "grouptree"  , partyTree ) ;
		return mapping.findForward ( "grouptree" );
	}
	
	
	private String generateGroupTreeStr ( GroupManager gm ,  boolean isLeaf , List list ,
			String locValue , String isTarget , java.util.Locale locale )
			throws CheckException {
    	OrgGroupTree orgGroupTree = new OrgGroupTree( ) ; 
    	orgGroupTree.setBaseName ( FuncMessageManager.get ( locale ).getMessage ( "group.tree.root" ) ) ;
    	orgGroupTree.setSrc ( "onLineUserAction.go?method=getGroupTrees&" ) ; 
    	orgGroupTree.setHref ( "onLineUserAction.go?method=onLineTabs&" ) ;
    	orgGroupTree.setRoot ( !isLeaf ) ;
    	orgGroupTree.setTarget ( "frmRight" ) ; 
    	orgGroupTree.setIsTarget ( isTarget ) ; 
    	orgGroupTree.setChildNodes (  list ) ;
    	if ( locValue != null )
    		orgGroupTree.setLocValue ( locValue ) ; 
    	return gm.generateGroupTreeStr( orgGroupTree ) ;
	}	
	
	public ActionForward onLineUserList ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		SessionUserInfo currentUser = getCurrentUser ( request );
        UserEmplyVo userEmplyVo = new UserEmplyVo();
        String obj =  request.getParameter ( "grpId"  ) ;
        if ( obj == null || "".equals ( obj ) )  return mapping.findForward( "glerror" ) ;
		Long grpId = Long.valueOf ( obj ) ; 

		List users = new ArrayList( ) ; 
		SessionRegistry sessionRegistry = ( SessionRegistry )getBean ( "sessionRegistry" ) ;
		Object[] objs = sessionRegistry.getAllPrincipals ( ) ;
		
		
		List list = new ArrayList( ) ; 
		if ( objs != null ) 
			for ( int i = 0 ; i < objs.length ; i ++ ) 
				users.add ( objs[ i ]  );

		int mxx = users.size ( ) ; 
		
		String[] loginnames = ( String [ ] ) users.toArray ( new String[ mxx >= mxxlim ? mxxlim : mxx ] );
		userEmplyVo.setLoginnames ( loginnames );
		
		if ( loginnames != null && loginnames.length > 0 ) 
			list = getGroupManager ( ).getOnlineUser ( userEmplyVo ) ;
		
		
		
		
		List onlineuserlist = new ArrayList();
		StringBuffer gourpIds = new StringBuffer( ) ;
		gourpIds.append ( grpId + StringPool.SLE) ;
		GroupRelVo  grpRel = getGroupManager ( ).loadGroupRel ( grpId ) ; 
		grpRel.setGrpPath ( grpRel.getGrpPath ( ) + StringPool.SLE ) ;
	
		List childs = getGroupManager ( ).getGroupsByPath ( grpRel ) ;
	 
		for ( java.util.Iterator iter = childs.iterator ( ) ; iter.hasNext ( ) ;  ) {
			GroupVo group = ( GroupVo ) iter.next ( ) ; 
			gourpIds.append ( group.getGrpId ( ) + StringPool.SLE );
		}
		
		
		for ( int i = 0 ; i < list.size ( ) ; i ++ ) {
			userEmplyVo = ( UserEmplyVo ) list.get ( i );
			String [ ] gids = gourpIds.toString ( ).split ( StringPool.SLE );
			for ( int j = 0 ; j < gids.length ; j ++ ) {
				if ( gids [ j ].toString ( ).trim ( ).equals (
						userEmplyVo.getGrpId ( ).toString ( ).trim ( ) ) ) {
					onlineuserlist.add ( userEmplyVo );
					break ;
				}
			}
		}
		userEmplyVo.setEmpList ( onlineuserlist );
		request.setAttribute ( Constants.CURRENT_URSER_MAX_ROLETYPE , new Integer( currentUser.getUserRoleType ( ) ) ) ;						
		request.setAttribute ( "userEmplyVo" , userEmplyVo );
		request.setAttribute ( "grpId" , grpId );
		request.setAttribute ( "onlinecount" , String.valueOf ( ( mxx >= mxxlim ? mxx : onlineuserlist.size ( )  ) ) );
		return mapping.findForward ( "onLineUserList" );
	}
	
	public ActionForward onLineTabs ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {
		String grpId = request.getParameter ( "grpId" ) ; 
		request.setAttribute ( "grpId" , ( grpId == null ? String
				.valueOf ( Constants.ORG_GROUP_BASE_VALUE ) : grpId ) );
		return mapping.findForward ( "onLineTabs" );
	}
	

	
	
	
	//强行签退
	
	public ActionForward unLineUser ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {
		String[] us = request.getParameterValues ( "usernames" ) ;
		SessionRegistry sessionRegistry = ( SessionRegistry )getBean ( "sessionRegistry" ) ;

		if ( us != null  ) 
			for ( int i = 0 ; i < us .length ; i ++  ) {
				String un = us[ i ] ;
				SessionInformation[] sessionInfos = sessionRegistry.getAllSessions ( un , true ) ;
				if ( sessionInfos != null )
					for ( int j = 0  ; j < sessionInfos.length ; j ++ ) 
						sessionRegistry.removeSessionInformation ( sessionInfos[ j ].getSessionId ( ) ) ; 
			}
		return mapping.findForward ( "success" );
	}
	
	 private GroupManager getGroupManager ( ) throws CheckException {
	        return OrgFactory.getGroupManager ( ) ;
	}
	
}
